package com.dao;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import java.sql.*;

/**
 * BaseDeo工具类
 *
 * @author wang_
 * @version 2024.3.4.1
 * @description
 * @date 2025/6/25
 */
public class BaseDeo {
	protected static final Logger            LOG = LogManager.getLogger(BaseDeo.class);
	public static          Connection        conn;
	private static         PreparedStatement stmt;
	
	/// 链接数据库
	public void linkConn() {
		conn = getConn();
	}
	
	/// 获取数据库连接
	private static Connection getConn() {
		Context ctx;
		try {
			ctx = new InitialContext();
			DataSource ds = (DataSource) ctx.lookup("java:comp/env/jdbc/mcmodwiki");
			conn = ds.getConnection();
		} catch (NamingException e) {
			LOG.error("获取数据源异常");
			LOG.error(e);
			throw new RuntimeException(e);
		} catch (SQLException e) {
			LOG.error("获取数据库连接异常");
			LOG.error(e);
			throw new RuntimeException(e);
		}
		return conn;
	}
	
	public void oldLinkConn() {
		conn = oldGetConn();
	}
	
	/**
	 * 获取数据库连接
	 *
	 * @return
	 */
	public static Connection oldGetConn() {
		try {
			Class.forName("com.mysql.cj.jdbc.Driver");
			String url = "jdbc:mysql://localhost:3306/mcmodwiki";
			return DriverManager.getConnection(url, "root", "1234");
		} catch (ClassNotFoundException e) {
			LOG.error("JDBC驱动加载异常！");
			LOG.error(e);
			throw new RuntimeException(e);
		} catch (SQLException e) {
			LOG.error("链接数据库异常！");
			LOG.error(e);
			throw new RuntimeException(e);
		}
	}
	
	public void closeAll() {
		closeAll(null);
	}
	
	/// 关闭数据库连接
	public void closeAll(ResultSet rs) {
		try {
			if (rs != null) {
				closeResultSet(rs);
			}
			if (stmt != null) {
				stmt.close();
			}
			if (conn != null) {
				conn.close();
			}
		} catch (SQLException e) {
			System.err.println("数据库关闭异常");
			LOG.error("数据库关闭异常");
			LOG.error(e);
		}
	}
	
	/// 关闭结果集
	public static void closeResultSet(ResultSet resultSet) {
		try {
			resultSet.close();
		} catch (SQLException e) {
			LOG.error("关闭结果集异常");
			LOG.error(e);
		}
	}
	
	/// 执行查询语句
	public ResultSet exeQuery(String sql, Object... params) {
		try {
			// 创建PreparedStatement对象
			createPreparedStatement(sql, params);
			return stmt.executeQuery();
		} catch (SQLException e) {
			LOG.error("执行查询异常，请检查SQL语句或输入的参数");
			LOG.error(e);
		}
		return null;
	}
	
	/// 创建PreparedStatement对象
	private static void createPreparedStatement(String sql, Object[] params) throws SQLException {
		stmt = conn.prepareStatement(sql);
		if (params != null) {
			// 设置参数
			for (int i = 0; i < params.length; i++) {
				stmt.setObject(i + 1, params[i]);
			}
		}
	}
	
	/// 执行更新语句
	public int exeUpdate(String sql, Object... params) {
		try {
			createPreparedStatement(sql, params);
			return stmt.executeUpdate();
		} catch (SQLException e) {
			System.err.println("执行更新异常，请检查SQL语句或输入的参数");
			LOG.error(e);
		}
		return 0;
	}
}
